<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useLoading } from '@sa/hooks';
import { fetchGetTenantPackageSelectList } from '@/service/api/system/tenant-package';
import { fetchCreateProducts, fetchUpdateProducts } from '@/service/api/business/products';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'TenantOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.System.Tenant | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule, patternRules } = useFormRules();
const { loading: packageLoading, startLoading: startPackageLoading, endLoading: endPackageLoading } = useLoading();
const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增产品',
    edit: '编辑产品'
  };
  return titles[props.operateType];
});

type Model = Api.Business.ProductsOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    name: '',
    price: 0,
    faceVerify: 0,
    identityVerify: 0
  };
}

type RuleKey = Extract<keyof Model, 'id' | 'name' | 'price' | 'faceVerify' | 'identityVerify'>;

const rules: Record<RuleKey, App.Global.FormRule | App.Global.FormRule[]> = {
  id: createRequiredRule('id不能为空'),
  name: createRequiredRule('产品名称不能为空'),
  price: createRequiredRule('价格不能为空'),
  faceVerify: createRequiredRule('人脸核验选择不能为空'),
  identityVerify: createRequiredRule('身份核验选择不能为空')
};

const packageOptions = ref<CommonType.Option<CommonType.IdType>[]>([]);
async function getPackageOptions() {
  startPackageLoading();
  const { error, data } = await fetchGetTenantPackageSelectList();
  if (!error) {
    packageOptions.value = data.map(item => ({
      label: item.packageName,
      value: item.packageId
    }));
  }
  endPackageLoading();
}

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  if (props.operateType === 'add') {
    const { name, price, faceVerify, identityVerify } = model;
    const { error } = await fetchCreateProducts({
      name,
      price,
      faceVerify,
      identityVerify
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { id, name, price, faceVerify, identityVerify } = model;
    const { error } = await fetchUpdateProducts({
      id,
      name,
      price,
      faceVerify,
      identityVerify
    });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    getPackageOptions();
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NDivider>基本信息</NDivider>
        <NFormItem label="产品名称" path="name">
          <NInput v-model:value="model.name" placeholder="请输入产品名称" />
        </NFormItem>
        <NFormItem label="产品价格" path="price">
          <NInputNumber v-model:value="model.price" placeholder="请输入产品价格" min="0" class="w-full" />
        </NFormItem>
        <NFormItem label="产品最高限价" path="saleMaxPrice">
          <NInputNumber v-model:value="model.price" placeholder="请输入产品最高限价" min="0" class="w-full" />
        </NFormItem>

        <NDivider>核验设置</NDivider>
        <NFormItem label="人脸核验" path="faceVerify">
          <NSwitch v-model:value="model.faceVerify as number" :round="false" :checked-value="0" :unchecked-value="1">
            <template #checked>开启</template>
            <template #unchecked>关闭</template>
          </NSwitch>
        </NFormItem>
        <NFormItem label="身份核验" path="identityVerify">
          <NSwitch
            v-model:value="model.identityVerify as number"
            :round="false"
            :checked-value="0"
            :unchecked-value="1"
          >
            <template #checked>开启</template>
            <template #unchecked>关闭</template>
          </NSwitch>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped>
.n-switch {
  --n-rail-color-active: #18a058;
  --n-rail-color: #d03050;
}
</style>
